<template>
  <div>
    <div>
      <div class="doctor-list">
        <div
          :class="classObject(tab)"
          @click="opinionTabChange(tab)"
          style="
            display: flex;
            justify-content: space-around;
            align-items: center;
            padding: 7px;
            width: 230px;
            margin-right: 15px;
            cursor: pointer;
            border-radius: 5px;
          "
          v-for="tab in opinionTabList"
          :key="tab.key"
        >
          <div>{{ tab.label }} <br />{{ tab.createTime }}</div>
          <div :class="lineClassObject(tab)" style="width: 3px; height: 36px"></div>
          <div>{{ tab.status }}</div>
        </div>
      </div>
      <el-row class="main-box">
        <div
          ref="layoutTemplate"
          class="diagnosis-template"
          v-show="isMyOpinionTab && diagnosisTemplateVisible"
        >
          <el-tabs v-model="diagnosisTemplateTabActive" @tab-click="diagnosisTemplateTabChange">
            <el-tab-pane label="机构模板" name="orgTemplate" style="padding-left: 20px">
            </el-tab-pane>
            <el-tab-pane label="我的模板" name="myTemplate" style="padding-left: 20px">
            </el-tab-pane>
          </el-tabs>
          <el-row>
            <el-input
              v-model="diagnosisTemplateFilterKey"
              placeholder="请输入关键字"
              class="input-form"
              size="mini"
            >
            </el-input>
            <el-button @click="diagnosisTemplateFilter" size="mini" class="button-list-item">
              过滤
            </el-button>
          </el-row>
          <el-tree
            node-key="id"
            v-loading="!isDiagnosisTemplateReady"
            :data="diagnosisTemplateList"
            :props="diagnosisTemplateProps"
            :load="diagnosisTemplateLoad"
            :default-expanded-keys="diagnosisExpandList"
            accordion
            lazy
          >
            <span slot-scope="{ node, data }" class="diagnosis-template-tree">
              <span class="diagnosis-template-tree-message">
                <el-button
                  :title="data.diagnoseLook"
                  @click="diagnosisTemplateNodeClick(data, node)"
                  size="mini"
                  type="text"
                  class="diagnosis-template-tree-message-text"
                >
                  {{ node.label }}
                </el-button>
                <el-button
                  v-if="diagnosisTemplateTabActive === 'orgTemplate'"
                  @click="diagnosisTemplateNodeCopy(node)"
                  size="mini"
                  type="text"
                >
                  复制
                </el-button>
              </span>
            </span>
          </el-tree>
        </div>
        <div style="flex-grow: 1;width:calc(100%-350px)">
          <el-row v-if="!isFinished" style="display: flex; flex-wrap: wrap;" align="middle">
            <!-- 模板显示按钮 -->
            <el-button
              v-if="isMyOpinionTab"
              @click="diagnosisTemplateVisibleChange"
              size="mini"
              type="primary"
              class="button-list-item"
            >
              {{ diagnosisTemplateVisible ? '收起' : '模板' }}
            </el-button>
            <el-button
              @click="inviteDialogOpen"
              v-if="
                isMyOpinionTab &&
                  tabActiveUserId == primaryDoctor.expertId &&
                  (isThereAFinalReview != 0 || thisOpinion.isFinished != 1)
              "
              class="button-list-item"
              type="primary"
              size="mini"
            >
              邀请专家
            </el-button>
            <el-button
              @click="consultationSave"
              v-if="isMyOpinionTab && (isThereAFinalReview != 0 || thisOpinion.isFinal != 1)"
              class="button-list-item"
              type="primary"
              size="mini"
            >
              暂存
            </el-button>

            <el-button
              v-if="
                tabActiveUserId == user.id &&
                  (isThereAFinalReview === 0 || thisOpinion.isFinal === 1)
              "
              @click="consultationIssue(0)"
              class="button-list-item"
              type="primary"
              size="mini"
            >
              发布
            </el-button>
            <el-button
              v-if="
                tabActiveUserId == user.id && isThereAFinalReview == 1 && thisOpinion.isFinal != 1
              "
              @click="consultationSubmit"
              class="button-list-item"
              type="primary"
              size="mini"
            >
              提交
            </el-button>
            <el-button @click="shareQRcode" class="button-list-item" type="primary" size="mini">
              分享二维码
            </el-button>
            <el-button
              v-if="isCollected"
              @click="cancelCollect"
              class="button-list-item"
              type="primary"
              size="mini"
            >
              取消收藏
            </el-button>
            <el-button v-else @click="collect" class="button-list-item" type="primary" size="mini">
              收藏
            </el-button>

            <!-- <el-button
                            :disabled="!isPrimarySpecialist&&opinionTabActive!=user.id"
                            class="button-list-item"
                            type="primary"
                            size="mini"
                            >
                            转终审
                            </el-button> -->
            <el-button
              @click="consultationSendBack"
              v-if="tabActiveUserId == user.id && thisOpinion.isFinished != 1"
              class="button-list-item"
              type="primary"
              size="mini"
            >
              退回
            </el-button>
            <el-button @click="goBack" class="button-list-item" type="primary" size="mini">
              返回
            </el-button>
            <el-button
              class="button-list-item"
              @click="addStaining"
              v-if="tabActiveUserId == user.id && thisOpinion.isFinished != 1"
              size="mini"
            >
              +特殊染色
            </el-button>
            <el-button
              class="button-list-item"
              @click="addMolecular"
              v-if="tabActiveUserId == user.id && thisOpinion.isFinished != 1"
              size="mini"
            >
              +分子病理
            </el-button>
            <el-button
              @click="addInc"
              v-if="tabActiveUserId == user.id && thisOpinion.isFinished != 1"
              class="button-list-item"
              size="mini"
            >
              +免疫组化
            </el-button>
          </el-row>
          <el-row v-else type="flex" align="middle">
            <!-- 模板显示按钮 -->
            <el-button
              v-if="isMyOpinionTab"
              @click="diagnosisTemplateVisibleChange"
              size="mini"
              class="button-list-item"
            >
              {{ diagnosisTemplateVisible ? '收起' : '模板' }}
            </el-button>
            <el-button
              @click="consultationRecycle"
              v-if="tabActiveUserId == user.id && isThereAFinalReview === 1"
              class="button-list-item"
              type="primary"
              size="mini"
            >
              回收报告
            </el-button>
            <el-button @click="reportViewClick" class="button-list-item" type="primary" size="mini">
              报告预览
            </el-button>
            <el-button @click="shareQRcode" class="button-list-item" type="primary" size="mini">
              分享二维码
            </el-button>

            <el-button
              v-if="isCollected"
              @click="cancelCollect"
              class="button-list-item"
              type="primary"
              size="mini"
            >
              取消收藏
            </el-button>
            <el-button v-else @click="collect" class="button-list-item" type="primary" size="mini">
              收藏
            </el-button>
            <el-button @click="goBack" class="button-list-item" type="primary" size="mini">
              返回
            </el-button>
            <el-button
              v-if="!isSendDoctor"
              class="button-list-item"
              type="primary"
              size="mini"
              @click="copyClick()"
              :disabled="orders.serviceStatus == 2"
            >
              复制（{{ thisOpinion.expertName + thisOpinion.createTime }}）
            </el-button>
          </el-row>

          <!-- <el-tabs v-model="opinionTabActive" @tab-click="opinionTabChange" type="card" style="margin-top: 10px">
            <el-tab-pane v-for="tab in opinionTabList" :name="tab.key" :label="tab.label" :key="tab.key">
              <span slot="label" :class="classObject(tab)"> {{ tab.label }}</span>
            </el-tab-pane>
          </el-tabs> -->

          <div v-if="isDispatched">
            <el-row class="line-text" type="flex" justify="space-between">
              <span class="content-text">病理诊断：</span>
            </el-row>
            <el-row style="margin-top: 10px">
              <el-input
                ref="myPathologyDiagnosisInput"
                :readonly="!isMyOpinionTab || isFinishedOfMyDiagnosis"
                v-model="opinionCurrent.input_binglizhenduan"
                placeholder="请书写病理诊断"
                :rows="pathologyDiagnosisInputRow"
                type="textarea"
                maxlength="500"
              >
              </el-input>
            </el-row>
            <el-row class="line-text" type="flex" justify="space-between" style="margin-top: 10px">
              <span class="content-text">建议及解释：</span>
            </el-row>
            <el-row style="margin-top: 10px">
              <el-input
                ref="mySuggestCont"
                :readonly="!isMyOpinionTab || isFinishedOfMyDiagnosis"
                v-model="opinionCurrent.input_jujian"
                placeholder="请书写相关建议及解释的内容"
                :rows="suggestContRow"
                type="textarea"
                maxlength="500"
              >
              </el-input>
            </el-row>
            <el-row class="line-text" type="flex" justify="space-between" style="margin-top: 10px">
              <span class="content-text">加做项目：</span>
            </el-row>
            <el-row style="margin-top: 10px">
              <!-- :readonly="!isMyOpinionTab || isFinishedOfMyDiagnosis" -->
              <el-input
                :readonly="true"
                v-model="opinionCurrent.input_extroProject"
                placeholder="加做项目的内容"
                :rows="2"
                type="textarea"
                maxlength="200"
              >
              </el-input>
            </el-row>
          </div>
          <div v-else>
            <span>未分配</span>
          </div>
          <div>
            <ConsultationPlus
              v-if="thisOpinion && thisOpinion.expertId"
              :orderId="orders.id"
              :diagnosisId="opinionTabActiveId"
              :orders="orders"
              ref="consultationPlus"
              @addPlus="addPlus"
            >
            </ConsultationPlus>
          </div>
        </div>
      </el-row>

      <el-dialog
        title="邀请专家"
        :visible.sync="inviteDialog.visible"
        :close-on-click-modal="false"
        :modal-append-to-body="false"
        append-to-body
        width="60%"
      >
        <base-table
          ref="inviteTable"
          v-loading="!inviteTable.isReady"
          :data="inviteTable.data"
          :header="inviteTable.header"
          :operation="inviteTable.operation"
          :pageInfo="inviteTable.pageInfo"
          :selected="true"
          :pageSizes="[5, 10, 15]"
          @selectedRow="inviteTableSelectedRow"
          @pageJumpTo="inviteTablePageJumpTo"
          @sizeChange="inviteTableSizeChange"
        >
        </base-table>
        <span slot="footer" class="dialog-footer" style="text-align: right">
          <el-button @click="inviteDialog.visible = false" size="mini">关闭</el-button>
          <el-button @click="inviteSpecialist" size="mini" type="primary">邀请</el-button>
        </span>
      </el-dialog>
    </div>

    <el-dialog title="分享二维码" :visible.sync="shareDialogVisible" width="30%">
      <el-row>{{ shareName }}医生邀请您参与这个病人的会诊</el-row>
      <!-- <el-row style="margin-top:15px">您可以复制此链接 ' {{appSrc}} ' 在浏览器中打开,或者用手机扫描下方二维码</el-row> -->
      <el-row style="margin-top: 15px"
        >操作方法：微信中识别图中二维码-点击右上角三个点--在浏览器中打开（打开手机的自动旋转功能，观看效果更好）</el-row
      >
      <div class="share-qrcode-box">
        <vue-qr
          :logo-src="logoSrc"
          :size="140"
          :margin="0"
          :auto-color="true"
          :dot-scale="1"
          :text="appSrc"
        />
      </div>
    </el-dialog>
    <div v-show="extroProjectDialogShow">
      <div class="section-label">
        加做项目付款信息<span style="font-size: 14px; color: red"
          >(请选择需要远程加做的项目,本机构可以做的请不要选择)</span
        >
      </div>
      <el-table
        :data="extraProjectPayList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="40" align="center" :selectable="selectable">
        </el-table-column>
        <el-table-column prop="doctorAdviceName" label="项目名" width="140"></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              @click="LookItemCheck(scope.row)"
              v-if="scope.row.resultUrl"
              type="text"
              size="small"
              >查看</el-button
            >
            <el-button
              @click="itemCheck(scope.row)"
              v-if="
                (scope.row.payStatus === '机构做' && isSendDoctor) ||
                  (scope.row.payStatus === '已付款' && !isSendDoctor)
              "
              type="text"
              size="small"
              >{{ scope.row.statusName === '已上传' ? '重新上传' : '上传' }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="typeName" label="项目类型" width="80"> </el-table-column>
        <el-table-column prop="doctorAdviceCost" label="价格" width="80"> </el-table-column>
        <el-table-column prop="statusName" label="当前状态" width="80"> </el-table-column>
        <el-table-column prop="createTime" label="提交时间" width="170"> </el-table-column>
        <el-table-column prop="payStatus" label="支付状态"> </el-table-column>
        <el-table-column label="备注" width="300">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.result"
              placeholder="请输入备注"
              class="input-form"
              size="mini"
            ></el-input>
            <el-button
              v-if="
                (scope.row.payStatus === '机构做' && isSendDoctor) ||
                  (scope.row.payStatus === '已付款' && !isSendDoctor)
              "
              @click="saveRemark(scope.row)"
              type="text"
              size="small"
              style="margin-left: 10px"
              >保存</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="btn-box">
        <span>共计费用 {{ totalAmount }} 元</span>
        <el-button type="primary" size="mini" @click="payClick" v-show="btnPayShow">付款</el-button>
      </div>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      title="加做项目费用支付"
      :visible.sync="payDialogVisible"
      width="670px"
      :append-to-body="true"
      @close="payDialogClose"
    >
      <div class="pay-box">
        <template v-if="!payDetails.status">
          <div class="money">
            <span>￥</span><span>{{ payDetails.orderAmount }}</span>
          </div>
          <div class="money-text">金额(元)</div>
          <div class="pay-qrcode-box">
            <div class="vxbg">
              <vue-qr
                v-if="payDetails.codeUrl"
                logo-src=""
                :size="140"
                :margin="0"
                :auto-color="true"
                :dot-scale="1"
                :text="payDetails.codeUrl"
              />
            </div>
          </div>
        </template>
      </div>
    </el-dialog>
    <!-- 上传资料 -->
    <el-dialog
      :close-on-click-modal="false"
      title="上传资料"
      :visible.sync="showUploadData"
      width="90%"
      @closed="cancelToUpload"
    >
      <el-upload
        ref="addItemDataUpload"
        multiple
        :action="`${imageURL}/upload`"
        :on-change="changeImages"
        :file-list="dialogImages"
        list-type="picture-card"
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="commitAppPic">提交</el-button>
        <el-button size="mini" @click="cancelToUpload">返回</el-button>
      </span>
    </el-dialog>
    <!-- 查看资料 -->
    <el-dialog
      :close-on-click-modal="false"
      title="查看资料"
      :visible.sync="lookshowUploadData"
      width="50%"
    >
      <viewer :images="dialogImages" ref="viewer">
        <img
          v-for="(img, index) in dialogImages"
          :src="img.url"
          :key="index"
          style="max-width: 100px; max-height: 100px; margin: 10px"
        />
      </viewer>

      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="lookshowUploadData = false">返回</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      title="选择终审医生"
      :visible.sync="finalDoctorListShow"
      width="50%"
    >
      <el-table :data="finalDoctorList" border style="width: 100%">
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">选择</el-button>
          </template>
        </el-table-column>

        <el-table-column prop="name" label="姓名"> </el-table-column>

        <el-table-column prop="phone" label="联系电话"> </el-table-column>
        <el-table-column prop="institutionName" label="所属机构"> </el-table-column>
        <el-table-column prop="createTime" label="注册时间"> </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import ConsultationDefault from '@/templates/ConsultationDefault'
import BaseTable from '@/templates/components/BaseTable'
import ConsultationPlus from '@/templates/components/ConsultationPlus'
import moment from 'moment'
import _ from 'lodash'
import VueQr from 'vue-qr'
const Qs = require('qs')

const opinionDataBase = {
  diagnosis: '',
  situation: ''
}

export default {
  name: 'ConsultationOpinion',
  components: {
    BaseTable,
    ConsultationPlus,
    VueQr
  },
  props: {
    orders: {
      type: Object,
      default: ConsultationDefault
    }
  },
  data() {
    return {
      imageURL: process.env.VUE_APP_ImageServiceURL, // 图片上传地址:
      shareName: this.$store.state.user.name,
      userId: this.$store.state.user.id,
      logoSrc: '',
      appSrc: '', //二维码包含的url字符串
      shareDialogVisible: false,
      extraProjectList: [], //点击医生时筛选出此医生所推荐的加做项目

      tabActiveUserId: 0,
      isThereAFinalReview: null, //0是无终审，1是有终审
      uArgs: this.$store.getters.getUArgs,
      user: this.$store.getters.getUser,
      // layoutTemplate 相关
      diagnosisTemplateTabActive: 'orgTemplate',

      isDiagnosisTemplateReady: false,
      diagnosisTemplateFilterKey: '',
      diagnosisTemplateList: [],
      diagnosisTemplateProps: {
        children: 'children',
        label: 'nodeName',
        isLeaf: 'isLeaf'
      },
      diagnosisExpandList: [],

      opinionTabList: [],
      opinionTabActive: '',

      opinionCurrent: {
        input_binglizhenduan: '',
        input_jujian: '',
        input_extroProject: ''
      },

      inviteDialog: {
        visible: false
      },
      inviteTable: {
        isReady: false,
        data: [],
        header: [
          {
            prop: 'name',
            label: '姓名',
            width: '100'
          },
          {
            prop: 'genderName',
            label: '性别',
            width: '55'
          },
          {
            prop: 'jobNumber',
            label: '工号',
            width: '120'
          },
          {
            prop: 'positionName',
            label: '职级',
            width: '60'
          },
          {
            prop: 'medicalTitleName',
            label: '职称',
            width: '60'
          },
          {
            prop: 'createTime',
            label: '注册时间',
            width: '160'
          },
          {
            prop: 'area',
            label: '所在地'
          },
          {
            prop: 'statusName',
            label: '用户状态',
            width: '100'
          }
        ],
        operation: [],
        pageInfo: {
          page: 1,
          size: 15,
          total: 0
        }
      },
      inviteSelected: new Set(),
      typeMap: {
        1: '特殊染色',
        2: '分子病理',
        3: '免疫组化'
      },
      payStatusList: {
        1: '待付款',
        2: '已付款',
        3: '机构做'
      },
      payDetails: {},
      timer: null,
      extraProjectPayList: [], //加做项目付款列表
      multipleSelection: [],
      totalAmount: 0.0,
      payDialogVisible: false,
      extroProjectDialogShow: false,
      reviewInstitutions: [],
      opinionTabActiveId: '',
      showUploadData: false,
      lookshowUploadData: false,
      dialogImages: [],
      imgURL: '',
      TransferData: '',
      finalDoctorListShow: false,
      finalDoctorList: [],
      pathologyDiagnosisInputRow: 3,
      suggestContRow: 3,
      diagnosisTemplateVisible: false
    }
  },
  computed: {
    //此次诊断有无终审
    isHaveFinalDoctor() {
      return this.orders.patients[0].expertDiagnosis.some(item => item.isFinal == 1)
    },
    btnPayShow() {
      return this.extraProjectPayList.some(item => {
        return item.status != '已付款'
      })
    },
    diagnosisTemplatesType() {
      return this.diagnosisTemplateTabActive === 'orgTemplate' ? 1 : 2
    },
    currentLevel() {
      return _.get(this.orders, 'currentLevel', -1)
    },
    //有终审 如果初诊不在,那终审也可直接输入后发布 所以如下判断注释掉
    isDispatched() {
      return true
      //   return this.orders.serviceStatus > 0
    },
    opinionList() {
      const detailList = this.orders.patients[0].expertDiagnosis
      return detailList === null ? [] : detailList
    },
    thisOpinion() {
      return this.opinionList.find(t => t.id === parseInt(this.opinionTabActive, 10))
        ? this.opinionList.find(t => t.id === parseInt(this.opinionTabActive, 10))
        : {}
    },
    isCopy() {
      return !(
        this.opinionTabList.some(n => n.expertId === this.user.id) &&
        this.opinionList.filter(n => n.expertId === this.user.id).some(n => !n.isFinished)
      )
    },
    isFinished() {
      if (!this.thisOpinion) {
        return false
      }
      return this.thisOpinion.isFinished == 1
    },
    isFinishedOfMyDiagnosis() {
      return _.get(this.thisOpinion, 'isFinished', 0) == 1
    },

    primaryDoctor() {
      return this.opinionList.find(t => t.type == 0) ? this.opinionList.find(t => t.type == 0) : {}
    },
    primaryOpinion() {
      return this.opinionList.find(t => t.expertId == this.user.id)
    },

    isPrimarySpecialist() {
      return this.user.id === _.get(this.primaryOpinion, 'expertId', 0)
    },
    isMyOpinionTab() {
      let _this = this
      if (this.isFinished == 1 && this.isPrimarySpecialist) return false
      if (
        _this.orders.patients.length == 0 ||
        _this.orders.patients[0].expertDiagnosis.length == 0
      ) {
        return false
      }
      return _this.orders.patients[0].expertDiagnosis.some(
        item => item.id == this.opinionTabActive && item.expertId == _this.user.id
      )
    },
    isCollected() {
      if (this.orders.isCollection === 0) {
        return false
      }
      if (this.orders.isCollection === 1) {
        return true
      }
    },
    isSendDoctor() {
      return this.userId === this.orders.userId ? true : false
    }
  },
  mounted() {
    this.getFinalDoctorList()
    this.getReviewInstitutions()
    // 诊断模板获取
    this.diagnosisTemplateRequest()
    this.opinionTabListInit()
    // await this.institutions(this.orders.serviceCenterId)

    console.log(
      this.$refs,
      this.$refs.myPathologyDiagnosisInput.$refs.textarea.offsetWidth,
      this.$refs.myPathologyDiagnosisInput.textLength,
      this.$refs.mySuggestCont.$refs.textarea.offsetWidth,
      this.$refs.mySuggestCont.textLength
    )
    setTimeout(() => {
      this.setTextAreaHeight()
    }, 1000)
  },
  methods: {
    setTextAreaHeight() {
      if (this.$refs.myPathologyDiagnosisInput.value) {
        const NDiagnosis = (this.$refs.myPathologyDiagnosisInput.value.match(/\n/g) || []).length
        const myPathologyDiagnosisInputRowCount =
          this.$refs.myPathologyDiagnosisInput.$refs.textarea.offsetWidth / 14
        const myPathologyDiagnosisInputRow =
          this.$refs.myPathologyDiagnosisInput.textLength / myPathologyDiagnosisInputRowCount
        this.pathologyDiagnosisInputRow = Math.ceil(myPathologyDiagnosisInputRow) + NDiagnosis
        const Nsuggest = (this.$refs.mySuggestCont.value.match(/\n/g) || []).length
        const mySuggestContRow =
          this.$refs.mySuggestCont.textLength / myPathologyDiagnosisInputRowCount
        this.suggestContRow = Math.ceil(mySuggestContRow) + Nsuggest
      }
    },
    diagnosisTemplateVisibleChange() {
      this.diagnosisTemplateVisible = !this.diagnosisTemplateVisible
    },
    classObject(tab) {
      if (this.opinionTabActiveId == tab.key) {
        return {
          activeStatus: true
        }
      }
      if (tab.isFinished == 0 || tab.isFinished == null) {
        return {
          warnStatus: true
        }
      } else {
        if (this.isHaveFinalDoctor) {
          if (tab.isFinal == 1) {
            return {
              greenStatus: true
            }
          }
          if (tab.isFinal == 0) {
            return {
              yellowGreen: true
            }
          }
        } else {
          return {
            greenStatus: true
          }
        }
      }
    },
    lineClassObject(tab) {
      if (tab.isFinished == 0 || tab.isFinished == null) {
        return {
          lineWarnStatus: true
        }
      } else {
        if (this.isHaveFinalDoctor) {
          if (tab.isFinal == 1) {
            return {
              lineGreenStatus: true
            }
          }
          if (tab.isFinal == 0) {
            return {
              lineYellowGreen: true
            }
          }
        } else {
          return {
            lineGreenStatus: true
          }
        }
      }
    },
    handleEdit(row) {
      this.$confirm(`确认选择${row.name}为终审医生?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.consultationIssue(row.id)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      this.finalDoctorListShow = true
    },
    getFinalDoctorList() {
      this.$axios({
        method: 'GET',
        url: `/institutions/getFinalDoctors`
      }).then(res => {
        if (res && res.data.code === 200) {
          this.finalDoctorList = res.data.data
        }
      })
    },
    changeImages(file, fileList) {
      this.imgURL = ''
      if (file.status === 'success') {
        fileList.forEach(ele => {
          if (ele.response) {
            this.imgURL += `${ele.response.url.slice(ele.response.url.indexOf('_') - 1)}|`
          }
        })
      }
    },
    cancelToUpload() {
      this.clearUploadFiles()
      this.showUploadData = false
    },
    commitAppPic() {
      // url修正为服务器返回链接
      let _this = this
      this.$axios({
        method: 'put',
        url: '/diagnosis/extra-project',
        data: { id: _this.TransferData, resultUrl: _this.imgURL }
      }).then(
        res => {
          if (res.data.code === 200) {
            _this.$message.info('添加成功')
            _this.showUploadData = false
            //   this[this.TransferDataKey].forEach((n, i) => {
            //     if (n.id == _this.TransferData) {
            //       this.$set(this[this.TransferDataKey][i], 'resultUrl', _this.imgURL)
            //     }
            //   })
            location.reload()
          }
        },
        err => {
          this.$message.info(`${err.response.data}`)
        }
      )
    },
    clearUploadFiles() {
      this.$refs.addItemDataUpload.clearFiles()
    },
    // 查看上传图片
    LookItemCheck(item) {
      debugger
      if (item.resultUrl) {
        this.dialogImages = []
        const imgList = item.resultUrl.split('|')
        const formatList = imgList.slice(0, -1)
        formatList.forEach(ele => {
          this.dialogImages.push({ name: 'img', url: this.imageURL + ele })
        })
      }
      this.lookshowUploadData = true
    },
    itemCheck(item, key) {
      console.log(key)
      this.showUploadData = true
      this.TransferData = item.id
      //   this.TransferDataKey = key
      if (item.url) {
        this.clearUploadFiles()
        this.dialogImages = []
        const imgList = item.url.split('|')
        const formatList = imgList.slice(0, -1)
        formatList.forEach(ele => {
          this.dialogImages.push({ name: 'img', url: this.imageURL + ele })
        })
      }
    },
    //备注保存
    saveRemark(row) {
      if (row.payStatus !== '已付款' && row.payStatus !== '机构做') {
        this.$message.warning('未付款不可保存结果')
      } else if (row.payStatus === '机构做' && this.isSendDoctor) {
        let _this = this
        this.$axios({
          method: 'put',
          url: '/diagnosis/extra-project',
          data: { id: row.id, result: row.result }
        }).then(
          res => {
            if (res.data.code === 200) {
              _this.$message.success('保存成功')
              this.$emit('consultationRequest')
              // this[this.TransferDataKey].forEach((n, i) => {
              //   if (n.id == _this.TransferData) {
              //     this.$set(this[this.TransferDataKey][i], 'resultUrl', _this.imgURL + '|')
              //   }
              // })
            }
          },
          err => {
            this.$message.info(`${err.response.data}`)
          }
        )
      }
    },
    //点击收藏按钮
    collect() {
      this.$axios({
        method: 'GET',
        url: `/collections/${this.orders.id}`
      }).then(res => {
        if (res && res.data.code === 200) {
          this.$message.success('收藏成功')
          this.orders.isCollection = 1
        }
      })
    },
    //点击取消收藏
    cancelCollect() {
      this.$axios({
        method: 'DELETE',
        url: `/collections/${this.orders.id}`
      }).then(res => {
        if (res && res.data.code === 200) {
          this.$message.success('取消收藏成功')
          this.orders.isCollection = 0
        }
      })
    },
    getReviewInstitutions() {
      this.$axios({
        method: 'GET',
        url: `/institutions/${this.orders.serviceCenterId}`
      }).then(res2 => {
        if (res2 && res2.data.code === 200) {
          const info = res2.data.data
          this.reviewInstitutions = info.reviewInstitutions
          this.extroProjectDialogShowFun()
        }
      })
    },
    extroProjectDialogShowFun() {
      if (this.isSendDoctor && (this.orders.ordersStatus === 3 || this.orders.ordersStatus === 4)) {
        this.extroProjectDialogShow = true
      }
      //   let autoAudit = false
      //   if (!!this.reviewInstitutions) {
      //     autoAudit = this.reviewInstitutions.some(item => {
      //       return item === this.orders.sendingHospitalId
      //     })
      //   }
      //   if (this.isSendDoctor) {
      //     if (autoAudit) {
      //       this.extroProjectDialogShow = false
      //     } else if (
      //       (this.orders.ordersStatus === 1 && this.orders.serviceStatus === 2) ||
      //       (this.orders.ordersStatus === 3 && this.orders.serviceStatus === 2) ||
      //       this.orders.ordersStatus === 4
      //     ) {
      //       this.extroProjectDialogShow = true
      //     }
      //   } else {
      //     this.extroProjectDialogShow = false
      //   }
    },

    shareQRcode() {
      this.shareDialogVisible = true
      this.appSrc = `http://www.aikeji.top:30002/share/index/${this.orders.uuid}`
      console.log(this.appSrc)
      //   this.appSrc = `192.168.1.134:3002/share/index/${this.orders.uuid}`
    },
    addPlus(arr) {
      let arrText = ''
      arr.forEach(item => {
        item.result = item.result ? item.result : item.resultUrl ? '结果已上传' : '暂未录入结果'
        arrText += item.doctorAdviceName + ':' + item.result + ';'
      })
      this.opinionCurrent.input_extroProject = arrText
      const id = parseInt(this.opinionTabActive, 10)
      this.extraProjectPayListFun(id)
    },
    reportViewClick() {
      const { state } = this.$store
      const { href } = this.$router.resolve({
        name: 'ConsultationReportView',
        path: '/detail/preview',
        query: {
          orderId: this.orders.id,
          authorization: this.$store.state.authorization,
          userId: state.user.id,
          consultationDetailId: this.opinionTabActive,
          uuid: this.orders.uuid
        }
      })
      window.open(href, '_blank')
    },
    // 诊断模板 - 标签页点击
    diagnosisTemplateTabChange() {
      this.diagnosisTemplateRequest()
    },
    // 诊断模板 - 获取诊断模板
    async diagnosisTemplateRequest() {
      this.isDiagnosisTemplateReady = false
      const param = {
        type: this.diagnosisTemplatesType,
        key: this.diagnosisTemplateFilterKey
      }

      const res = await this.$axios({
        method: 'get',
        url: '/diagnose-templates',
        params: param
      })
      if (res && res.data.code === 200) {
        this.diagnosisTemplateList = []
        res.data.data.forEach(e => {
          this.diagnosisTemplateList.push({
            id: e.id,
            nodeName: e.nodeName,
            isLeaf: e.isLeaf,
            children: []
          })
        })
      } else {
        this.$message.info('请求失败')
      }
      this.isDiagnosisTemplateReady = true
    },
    async diagnosisTemplateFilter() {
      if (this.diagnosisTemplateFilterKey === '') {
        this.diagnosisTemplateRequest()
        return
      }

      this.isDiagnosisTemplateReady = false
      const param = {
        type: this.diagnosisTemplatesType,
        key: this.diagnosisTemplateFilterKey
      }

      const res = await this.$axios({
        method: 'get',
        url: '/diagnose-templates',
        params: param
      })

      if (res && res.data.code === 200) {
        // 确定默认展开节点
        this.diagnosisExpandList = []
        if (res.data.data.length > 0) {
          const firstNode = res.data.data[0]
          this.diagnosisExpandList.push(firstNode.id)
          if (_.get(firstNode, 'children.length', 0)) {
            const secondNode = firstNode.children[0]
            this.diagnosisExpandList.push(secondNode.id)
            if (_.get(secondNode, 'children.length', 0)) {
              const thirdNode = secondNode.children[0]
              this.diagnosisExpandList.push(thirdNode.id)
            }
          }
        }
        // 确定树的数据
        this.diagnosisTemplateList = []
        res.data.data.forEach(e => {
          this.diagnosisTemplateList.push(e)
        })
        this.isDiagnosisTemplateReady = true
      } else {
        this.$message.info('请求失败')
        this.isDiagnosisTemplateReady = true
      }
    },
    // 诊断模板 - 节点加载
    async diagnosisTemplateLoad(node, resolve) {
      // 无效 id
      if (!node.data.id) {
        resolve([])
      } else if (this.diagnosisTemplateFilterKey === '') {
        const res = await this.$axios({
          method: 'GET',
          url: `/diagnose-templates/${node.data.id}`
        })
        if (res && res.data.code === 200) {
          resolve(res.data.data)
        }
      } else {
        // 叶子节点
        if (node.level >= 3) resolve([])
        if (node.data.parentId === 0) {
          // 根节点 - 展开
          this.diagnosisTemplateList.forEach(rootNode => {
            if (rootNode.id === node.data.id) {
              const results = rootNode.children
              resolve(results)
            }
          })
        } else {
          // 中间节点 - 展开
          this.diagnosisTemplateList.forEach(rootNode => {
            if (rootNode.children) {
              rootNode.children.forEach(secondLevel => {
                if (secondLevel.id === node.data.id) {
                  const results = secondLevel.children
                  resolve(results)
                }
              })
            }
          })
        }
      }
    },
    // 诊断模板 - 节点点击
    diagnosisTemplateNodeClick(data, node) {
      if (this.isMyOpinionTab && data.isLeaf) {
        console.log(this.opinionCurrent)
        debugger
        if (this.opinionCurrent.input_binglizhenduan) {
          this.opinionCurrent.input_binglizhenduan += '\n'
          this.opinionCurrent.input_binglizhenduan += '病理诊断：' + node.data.diagnoseLook
          this.opinionCurrent.input_binglizhenduan += '\n'
          this.opinionCurrent.input_binglizhenduan += '镜下所见：' + node.data.nodeName
        } else {
          this.opinionCurrent.input_binglizhenduan = '病理诊断：' + node.data.diagnoseLook
          this.opinionCurrent.input_binglizhenduan += '\n'
          this.opinionCurrent.input_binglizhenduan += '镜下所见：' + node.data.nodeName
        }
        // if (this.opinionCurrent.input_jujian) {
        //   this.opinionCurrent.input_jujian += '\n'
        //   this.opinionCurrent.input_jujian += node.data.diagnoseLook
        // } else {
        //   this.opinionCurrent.input_jujian = node.data.diagnoseLook
        // }
        setTimeout(() => {
          this.setTextAreaHeight()
        }, 1000)
        this.$message.success('添加成功')
      }
    },
    // 诊断模板 - 节点复制
    async diagnosisTemplateNodeCopy(node) {
      const res = await this.$axios({
        method: 'POST',
        url: `/diagnose-templates/copy?id=${node.data.id}`
      })

      if (res && res.data.code === 200) {
        this.$message.success('复制成功')
      } else {
        this.$message.warning('复制失败')
      }
    },
    opinionTabListInit() {
      let _this = this
      _this.opinionTabList = []
      let opinionList = []
      const opinionListCopy = _this.orders.patients[0].expertDiagnosis
      //如果登录人是诊断里的医生 先排到前面
      if (opinionListCopy.some(t => t.expertId == _this.user.id)) {
        //我的报告排列在前面，我的报告里未发布的最前面，其它医生的报告在后面
        let aArr = opinionListCopy.filter(item => {
          return item.expertId == _this.user.id
        })
        let bArr = opinionListCopy.filter(item => {
          return item.expertId != _this.user.id
        })
        opinionList = aArr.concat(bArr)
      } else {
        opinionList = _this.orders.patients[0].expertDiagnosis
      }

      //   const doctorNotDiagnosis = opinionList.some(
      //     item => item.isFinal == 0 && (item.isFinished == null || item.isFinished == 0)
      //   )
      const finalDoctorStatus = opinionList.some(item => item.isFinal == 1 && item.type == 2)
      if (finalDoctorStatus) {
        this.isThereAFinalReview = 1
      } else {
        this.isThereAFinalReview = 0
      }

      //   if (doctorNotDiagnosis) {
      //     opinionList.forEach(t => {
      //       if (t.isFinal == 0) {
      //         _this.opinionTabList.push({
      //           consultationDetailId: t.consultationDetailId,
      //           key: t.id.toString(),
      //           expertId: t.expertId,
      //           label:
      //             t.isFinal == 1
      //               ? t.expertName +
      //                 '(终审)' +
      //                 t.createTime +
      //                 (t.isFinished == 1 ? '已发布' : '未发布')
      //               : t.type == 1
      //               ? t.expertName +
      //                 '(邀请)' +
      //                 t.createTime +
      //                 (t.isFinished == 1 ? '已发布' : '未发布')
      //               : t.expertName +
      //                 '(诊断)' +
      //                 t.createTime +
      //                 (t.isFinished == 1 ? '已发布' : '未发布'),
      //           isFinished: t.isFinished,
      //           isFinal: t.isFinal
      //         })
      //       }
      //     })
      //   } else {

      //   }
      opinionList.forEach(t => {
        if (t.expertId != null) {
          _this.opinionTabList.push({
            consultationDetailId: t.consultationDetailId,
            key: t.id.toString(),
            expertId: t.expertId,
            // label:
            //   t.isFinal == 1
            //     ? t.expertName + '(终审)' + t.createTime + (t.isFinished == 1 ? '已发布' : '未发布')
            //     : t.type == 1
            //       ? t.expertName + '(邀请)' + t.createTime + (t.isFinished == 1 ? '已发布' : '未发布')
            //       : t.expertName + '(诊断)' + t.createTime +
            //       (t.isFinished == 1 ? '已发布' : '未发布'),
            isFinished: t.isFinished,
            isFinal: t.isFinal,
            label:
              t.isFinal == 1
                ? t.expertName + '(终审)'
                : t.type == 1
                ? t.expertName + '(邀请)'
                : t.expertName + '(诊断)',
            status: t.isFinished == 1 ? '已发布' : '未发布',
            createTime: t.createTime
          })
        }
      })

      let primaryOpinion = _this.opinionTabList.find(t => t.expertId == _this.user.id)
      if (this.isSendDoctor) {
        const isHaveFinalDoctor = _this.orders.patients[0].expertDiagnosis.some(
          item => item.isFinal == 1
        )
        if (isHaveFinalDoctor) {
          //有终审的医生tab列表
          _this.opinionTabList = _this.opinionTabList.filter(item => {
            return item.isFinished === 1 && item.isFinal == 1
          })
          primaryOpinion = _this.opinionTabList[_this.opinionTabList.length - 1]
        } else {
          //无终审的医生tab列表
          _this.opinionTabList = _this.opinionTabList.filter(item => {
            return item.isFinished === 1 && item.isFinal == 0
          })
          primaryOpinion = _this.opinionTabList[_this.opinionTabList.length - 1]
        }
      }
      _this.opinionTabActive = primaryOpinion.key
      console.log('_this.opinionTabActive ', _this.opinionTabActive)
      _this.opinionDataInit()
      const id = parseInt(this.opinionTabActive, 10)
      this.extraProjectPayListFun(id)
    },
    getOpinionBySpecialistId(id) {
      // const currentButInfo = this.opinionList.find(t => t.id == Number(id))
      // this.opinionList.forEach((item, index) => {
      //   if (currentButInfo.expertId == item.expertId && item.detailString) {
      //     currentButInfo.detailString = item.detailString
      //   }
      // })
      // return currentButInfo
      return this.opinionList.find(t => t.id == Number(id))
    },
    // 意见 - 查看他人时，保存表单数据到缓存，加载缓存数据到表单
    opinionTabChange(activeTab) {
      const _this = this
      _this.setOptionCurrent(Number(activeTab.key))
    },

    setOptionCurrent(id) {
      console.log('id', id)
      const _this = this
      _this.opinionTabActiveId = id.toString()
      const opinion = _this.getOpinionBySpecialistId(id)
      _this.tabActiveUserId = opinion.expertId
      console.log('opinion', opinion)
      _this.opinionCurrent =
        opinion.detailString != null
          ? JSON.parse(_.get(opinion, 'detailString', {}))
          : {
              input_binglizhenduan: '',
              input_jujian: '',
              input_extroProject: ''
            }
    },
    opinionDataInit() {
      const id = parseInt(this.opinionTabActive, 10)
      this.setOptionCurrent(id)
    },
    // 复制
    async copyClick() {
      const that = this
      // console.log(this.opinionTabList)
      // console.log(this.opinionList?.find(n => n.expertId === this.user.id && n.isFinished !== 1))
      // tId终审报告   rId要复制的那份报告
      const tId =
        that.opinionList?.find(n => n.expertId === that.user.id && n.isFinished !== 1)?.id || ''

      const rId = that.opinionTabList?.find(n => n.key === that.opinionTabActiveId)?.key || ''
      if (!tId || !rId) {
        return
      }
      that
        .$confirm('此操作将复制他人诊断报告，删除您的诊断报告, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(async () => {
          const res = await that.$axios({
            url: '/diagnosis_data/duplicate/' + rId + '/' + tId,
            method: 'get'
          })
          if (res.data.code == 200) {
            if (res.data.data === true) {
              that.$message({
                type: 'success',
                message: '复制成功!'
              })
              that.$emit('consultationRequest')
            }
          }
        })

      // if (res && res.data.code === 200) {
      //   this.$message.success('保存成功')
      //   const opinion = _this.getOpinionBySpecialistId(_this.thisOpinion.id)
      //   opinion.detailString = JSON.stringify(_this.opinionCurrent)
      // } else {
      //   this.$message.error('保存失败')
      // }
    },
    // 会诊 - 保存
    async consultationSave() {
      let _this = this
      const res = await this.$axios({
        url: '/consultationsDetail',
        method: 'POST',
        data: {
          id: _this.thisOpinion.consultationDetailId,
          expertDiagnosisId: _this.thisOpinion.id,
          detailString: JSON.stringify(_this.opinionCurrent)
        }
      })

      if (res && res.data.code === 200) {
        this.$message.success('暂存成功')
        const opinion = _this.getOpinionBySpecialistId(_this.thisOpinion.id)
        opinion.detailString = JSON.stringify(_this.opinionCurrent)
      } else {
        this.$message.error('保存失败')
      }
    },
    consultationSubmit() {
      this.finalDoctorListShow = true
    },
    // 会诊 - 发布
    async consultationIssue(expertId) {
      let _this = this
      let whetherToAdd = 0
      const maxId = Math.max.apply(
        Math,
        _this.extraProjectPayList.map(item => {
          return item.id
        })
      )
      if (_this.extraProjectPayList.length > 0) {
        const payStatus =
          _this.extraProjectPayList.find(item => {
            return item.id == maxId
          }).payStatus === '待付款'
        if (!!payStatus) {
          whetherToAdd = 1 //有加座
        } else {
          whetherToAdd = 0 //无加座
        }
      }
      const detailString = JSON.stringify(this.opinionCurrent)
      const res = await _this.$axios({
        url: `/consultations/${_this.thisOpinion.id}/${_this.isThereAFinalReview}/${whetherToAdd}/${expertId}/issue`,
        method: 'PUT',
        data: {
          detailString
        }
      })
      if (res && res.data.code === 200) {
        _this.$message.success('发布成功')
        if (_this.isThereAFinalReview === 0 || _this.thisOpinion.isFinal === 1) {
          if (whetherToAdd === 1) {
            let autoAudit = false
            if (!!_this.reviewInstitutions) {
              autoAudit = _this.reviewInstitutions.some(item => {
                return item === _this.orders.sendingHospitalId
              })
            }
            const extraProjectsIdsArr = _this.extraProjectPayList.filter(item => {
              return item.payStatus === '待付款'
            })
            if (autoAudit) {
              const mData = {
                ordersNumber: _this.orders.serialNumber,
                extraProjectsIds: extraProjectsIdsArr.map(n => n.id),
                institutionId: _this.orders.serviceCenterId
              }
              _this
                .$axios({
                  method: 'POST',
                  url: `orders/create/order/extra`,
                  data: mData
                })
                .then(res => {
                  if (res.data.code === 200) {
                    this.$message.success('会诊机构已设置自动过审,已自动进入下一流程')
                    _this.$emit('consultationRequest')
                  }
                })
            } else {
              _this.$emit('consultationRequest')
            }
          } else {
            _this.$emit('consultationRequest')
          }
        } else {
          _this.$emit('consultationRequest')
        }
      } else {
        _this.$message.error('发布失败')
      }
    },

    // 会诊 - 退回
    consultationSendBack() {
      this.$prompt('请输入退回说明', '退回说明', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.*[^\s]/,
        inputErrorMessage: '退回说明不能为空'
      }).then(async ({ value }) => {
        const res = await this.$axios({
          method: 'POST',
          url: `orders/sendBack`,
          data: { pid: this.orders.id, pserviceStatus: 0, returnReason: value }
        })

        if (res && res.data.code === 200) {
          this.$message.info(res.data.data.message)
          this.$router.go(-1)
        }
      })
    },
    // 会诊 - 回收
    async consultationRecycle() {
      const res = await this.$axios({
        method: 'GET',
        url: `/expert/diagnosis/callback/${this.opinionTabActiveId}/${this.orders.id}`
      })

      if (res && res.data.code === 200) {
        this.$message.success('回收成功')
        this.$emit('consultationRequest')
      } else {
        this.$message.warning(res.data.data)
      }
    },
    goBack() {
      this.$router.go(-1)
    },
    inviteDialogOpen() {
      this.inviteTableDataRequest()
      this.inviteDialog.visible = true
    },
    inviteTablePageJumpTo(val) {
      this.inviteTable.pageInfo.page = val
      this.inviteTableDataRequest()
    },
    inviteTableSizeChange(val) {
      this.inviteTable.pageInfo.size = val
      this.inviteTableDataRequest()
    },
    inviteTableSelectedRow(selectedRow) {
      this.inviteSelected = _.clone(selectedRow)
    },
    inviteTableDataRequest() {
      this.inviteTable.isReady = false
      try {
        this.$axios({
          method: 'GET',
          url: `/consultations/${this.orders.serviceCenterId}/${this.orders.patients[0].id}/invitation-experts`,
          params: {
            page: this.inviteTable.pageInfo.page - 1,
            size: this.inviteTable.pageInfo.size
          }
        }).then(res => {
          if (res && res.data.code === 200) {
            // 分页处理
            this.inviteTable.pageInfo = {
              total: res.data.pageInfo.total,
              page: res.data.pageInfo.page + 1,
              size: res.data.pageInfo.size
            }
            // 数据处理
            this.inviteTable.data = []
            if (res.data.data) {
              res.data.data.forEach((t, index) => {
                const user = {
                  index,
                  id: t.id,

                  name: t.name,
                  genderName: t.genderName,
                  jobNumber: t.jobNumber,
                  positionName: t.positionName,
                  medicalTitleName: t.medicalTitleName,
                  createTime: moment(t.createTime).format('YYYY-MM-DD'),
                  statusName: t.status ? '冻结' : '正常',
                  area: t.area,
                  idCardStatusName: '',
                  qualityStatusName: '',

                  roleList: t.roles,
                  status: t.status
                }

                this.inviteTable.data.push(user)
              })
            }
          }

          this.inviteTable.isReady = true
        })
      } catch (e) {
        this.inviteTable.isReady = true
        this.$message.warning('请求失败')
      }
    },
    async inviteSpecialist() {
      const expertIdArr = []
      this.inviteSelected.forEach(index => {
        expertIdArr.push(this.inviteTable.data[index].id)
      })
      const res = await this.$axios({
        method: 'PUT',
        url: `/consultations/${this.orders.patients[0].id}/invite`,
        params: {
          expertIdArr
        },
        paramsSerializer(params) {
          return Qs.stringify(params, { arrayFormat: 'repeat' })
        }
      })

      if (res && res.data.code === 200) {
        this.$message.success('邀请成功')
        this.$emit('consultationRequest')
        this.inviteDialog.visible = false
      } else {
        this.$message.warning('邀请失败')
      }
    },

    addStaining() {
      this.$refs.consultationPlus.addDyeingHandelClick()
    },
    addMolecular() {
      this.$refs.consultationPlus.addMolecularHandelClick()
    },
    addInc() {
      this.$refs.consultationPlus.addIncHandelClick()
    },
    async extraProjectPayListFun(id) {
      const that = this
      const res = await that.$axios({
        method: 'GET',
        url: `/diagnosis/extra-project/${that.orders.patients[0].id}`
      })
      if (res.data.code === 200) {
        that.extraProjectPayList =
          res.data.data
            .map(n => ({
              ...n,
              statusName: n.resultUrl ? '已上传' : '未上传',
              payStatus: that.payStatusList[n.payStatus],
              typeName: that.typeMap[n.type]
            }))
            .filter(n => n.consultationId == id) || []
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.totalAmount = (
        this.multipleSelection.reduce((total, n) => total + (n.doctorAdviceCost || 0) * 100, 0) /
        100
      ).toFixed(2)
    },
    async payClick() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          offset: 100,
          showClose: true,
          type: 'error',
          message: '请选择加做项目信息！'
        })
        return
      } else {
        this.$confirm('您将要进行付款，是否继续？', '确认付款', {
          distinguishCancelAndClose: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          if (this.orders.canWeChat === 0) {
            //机构服务设置里不需要网上支付
            this.noPayFun()
          } else if (this.orders.canWeChat === 1) {
            //机构服务设置里需要网上支付

            this.extraOrderWxPay()
            this.payDialogVisible = true
          }
        })
      }
    },
    async extroProjectNoCheck(a, b) {
      const arr = [...a, ...b]
      const ids = arr.filter(item => {
        return !(a.includes(item) && b.includes(item))
      })
      const res = await this.$axios({
        method: 'POST',
        url: `/diagnosis/extra-project/updatePayStatus`,
        data: JSON.stringify(ids)
      })
    },
    selectable(row) {
      return row.payStatus === '待付款'
    },
    payDialogClose() {
      this.payDialogVisible = false
      clearInterval(this.timer)
    },
    async noPayFun() {
      const that = this
      const mData = {
        ordersNumber: that.orders.serialNumber,
        extraProjectsIds: that.multipleSelection.map(n => n.id),
        institutionId: that.orders.serviceCenterId
      }
      const res = await that.$axios({
        method: 'POST',
        url: `orders/create/order/extra`,
        data: mData
      })
      if (res.data.code === 200) {
        that.$emit('consultationRequest')
        that.$message.success('会诊机构设置了无需网上支付,已自动进入下一流程')
      }
    },
    async extraOrderWxPay() {
      const that = this
      const mData = {
        body: '爱可及医疗商品', //商品说明：默认“爱可及医疗商品”
        ordersNumber: this.orders.serialNumber, //订单编号
        extraProjectsIds: this.multipleSelection.map(n => n.id),
        institutionId: that.orders.serviceCenterId
      }
      const res = await that.$axios({
        method: 'POST',
        url: `wx/pay/create/order/extra`,
        data: mData
      })

      const _totalOrderAmount = this.multipleSelection.reduce(
        (total, n) => total + (n.doctorAdviceCost || 0) * 100,
        0
      )
      if (res.data.code === 200) {
        this.payDetails = {
          status: false,
          orderAmount: (_totalOrderAmount / 100).toFixed(2),
          ...res.data.data
        }
        this.timer = setInterval(() => {
          this.wxQueryPay()
        }, 2000)
      }
    },
    async wxQueryPay() {
      const that = this
      const institutionId = that.orders.serviceCenterId
      const res = await that.$axios({
        method: 'GET',
        url: `/wx/pay/query`,
        params: {
          pOrdersDetailNo: this.payDetails.orderDetailNo,
          institutionId: institutionId,
          extraProjectsIds: this.multipleSelection.map(n => n.id).join()
        }
      })
      if (res.data.code === 200) {
        if (res.data.data.returnCode == 'SUCCESS') {
          this.payDetails.status = true
          //如果有没选的 那就是申请机构可以自己做的 把没选的改一下状态
          if (this.extraProjectPayList.length != this.multipleSelection.length) {
            const filterHavePayArry = this.extraProjectPayList.filter(
              item => item.payStatus != '已付款'
            )
            const a = filterHavePayArry.map(n => n.id)
            const b = this.multipleSelection.map(n => n.id)
            this.extroProjectNoCheck(a, b)
          }
          this.payDialogClose()
          this.$emit('consultationRequest')
          //   this.opinionTabListInit()
        }
      }
    }
  }
}
</script>

<style scoped>
.diagnosis-template-tree {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.diagnosis-template-tree-message {
  font-size: 14px;
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.diagnosis-template-tree-message-text {
  color: #000;
  width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: left;
}
.share-qrcode-box {
  padding: 20px;
  margin: 20px auto;
  border-top: 1px solid #dcdcdc;
  display: flex;
  justify-content: space-around;
}

.btn-box {
  padding: 15px 0;
  display: flex;
  justify-content: space-between;
}

.pay-box {
  margin: 0 auto;
  padding: 20px 0;
}

.pay-box .money-text {
  text-align: center;
}

.pay-box .money {
  text-align: center;
  color: #226eff;
  font-size: 30px;
}

.pay-box .pay-qrcode-box {
  padding: 20px;
  margin: 20px auto;
  border-top: 1px solid #dcdcdc;
  display: flex;
  justify-content: space-around;
}

.vxbg {
  width: 243px;
  height: 243px;
  padding: 83px 49px;
  box-sizing: border-box;
  background-image: url('/images/index/vx.png');
}

.activeStatus {
  background-color: #e6a23c;
  color: #ffffff;
}

.warnStatus {
  background-color: #ffffff;
  border: 1px solid #ff4343;
  color: #ff4343;
}

.greenStatus {
  background-color: #266eff;
  color: #ffffff;
}

.yellowGreen {
  border: 1px solid #266eff;
  background-color: #fff;
  color: #266eff;
}

.lineWarnStatus {
  background-color: #d8d8d8;
}

.lineGreenStatus {
  background-color: #ffffff;
}

.lineYellowGreen {
  background-color: #d8d8d8;
}

.doctor-list {
  display: flex;
}

.main-box {
  display: flex;
  padding: 10px;
  margin-top: 10px;
  border: 1px solid #e6e6e6;
  border-radius: 10px;
}

.diagnosis-template {
  margin-right: 20px;
  border: 1px solid #e6e6e6;
  border-radius: 10px;
  box-sizing: border-box;
  width: 300px;
}

::v-deep #tab-orgTemplate {
  padding-left: 20px;
}
.button-list-item {
  margin-bottom: 10px;
}
::v-deep .el-textarea {
  width: 99%;
}
</style>
